#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtConcurrent>
#include <QQmlEngine>
#include <QThread>
#include "pgloader.h"
#include "pgmodel.h"

#include "plugin/PluginHandler.h"
#include "plugin/choicemodel.h"
#include "plugin/filedialoghandler.h"

#include "tcpmanager.h"


void init();
void async();
void resigter();
void dynamic_load(QQmlApplicationEngine& engine);

int main(int argc, char *argv[])
{
    init();
    resigter();
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    app.setOrganizationName("PanGuSegment");
    QQmlApplicationEngine engine;

    async();
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    dynamic_load(engine);
//    TcpManager::instance()->connectToHost(QString("mytest"), QString("127.0.0.1"), 43800);
    return app.exec();
}

void resigter()
{
    qmlRegisterSingletonInstance("PluginHandler", 1, 0, "PluginHandler", PluginHandler::instance());
    qmlRegisterSingletonInstance("PGModel", 1, 0, "PGModel", PGModel::instance());
    qmlRegisterSingletonInstance("ChoiceModel", 1, 0, "ChoiceModel", ChoiceModel::instance());
    qmlRegisterSingletonInstance("FileDialogHandler", 1, 0, "FileDialogHandler", FileDialogHandler::instance());
}

void init()
{
    // 设置输出格式
    qSetMessagePattern("[%{time yyyyMMdd h:mm:ss.zzz}] "
                       "%{if-debug}[DEBUG]%{endif}"
                       "%{if-info}[INFO]%{endif}"
                       "%{if-warning}[WARN]%{endif}"
                       "%{if-critical}[CRIT]%{endif}"
                       "%{if-fatal}[FATAL]%{endif}"
                       "[%{threadid}] [%{function}] "
                       "%{file}:%{line} - %{message}");



    // 连接SLOT和SIGNAL
    QObject::connect(PGLoader::instance(), SIGNAL(loadComplete()),
                     ChoiceModel::instance(), SLOT(onPGLoaderLoadComplete()));
}

void async()
{
    // 设置连接管理为异步模式
    TcpManager* manager = TcpManager::instance();
    manager->async();
}

void dynamic_load(QQmlApplicationEngine& engine)
{
    QQmlComponent mainPage(&engine, QUrl("qrc:/ChoicePage.qml"));
    QObject* objMainPage = mainPage.create();
    if (objMainPage != nullptr) {
        qDebug() << "加载首页完成";
        PGModelData *data = new PGModelData;
        data->m_name = "首页",
        data->m_page = dynamic_cast<QQmlComponent*>(objMainPage);
        PGModel::instance()->append(data);
    } else {
        qDebug() << "加载首页失败";
    }

    QQmlComponent addBtn(&engine, QUrl("qrc:/plugin/AddPluginButton.qml"));
    QObject* objAddBtn = addBtn.create();


    /* 加载外部插件 */
    PGLoader* loader = PGLoader::instance();
    loader->load(engine);

    if (objAddBtn != nullptr) {
        ChoiceModelData data;
        data.m_name = "添加新组件";
        data.m_cbtn = dynamic_cast<QQmlComponent*>(objAddBtn);
        ChoiceModel::instance()->append(data);
        qDebug() << "加载添加按钮成功";
    } else {
        qDebug() << "加载添加按钮失败";
    }
}


//    auto qlist = engine->rootObjects();
//    auto window = qlist.first();
//    qDebug() << window->findChild<QObject*>("myButton");
//    QObject::connect(window, SIGNAL(qmlSig(int, QString)),
//                     MyObject::getInstance(), SLOT(cppSlot(int, QString)));

//    QObject::connect(MyObject::getInstance(), SIGNAL(cppSig(QVariant, QVariant)),
//                     window, SLOT(qmlSlot(QVariant, QVariant)));
//    QQmlEngine engine;

//    QVariant res;
//    QVariant arg1 = "首页", arg2 = QVariant::fromValue(obj);
//    /* cpp调用qml端的函数 */
//    QMetaObject::invokeMethod(window, "addToModel",
//                              Q_RETURN_ARG(QVariant, res),
//                              Q_ARG(QVariant, arg1),
//                              Q_ARG(QVariant, arg2));
